package com.sunlands.deskmate.service;

import com.sunlands.deskmate.client.DeskMateGroupService;
import com.sunlands.deskmate.client.LiveVideoService;
import com.sunlands.deskmate.client.UserFriendService;
import com.sunlands.deskmate.client.vo.DialogVO;
import com.sunlands.deskmate.message.entity.Messages;
import com.sunlands.deskmate.message.enums.MessageType;
import com.sunlands.deskmate.utils.RedisUtil;
import com.sunlands.deskmate.vo.GroupUserVO;
import com.sunlands.deskmate.vo.TzUserFriendInfo;
import com.sunlands.deskmate.vo.response.BusinessResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DialogRecordServiceImpl {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private LiveVideoService liveVideoService;

    @Autowired
    private DeskMateGroupService deskMateGroupService;

    @Autowired
    private UserFriendService userFriendService;

    public List<Long> allLearnRoomUsers(Long roomId){
        return liveVideoService.allRoomUsers(roomId)
                .getData()
                .stream()
                .map(DialogVO::getUserId)
                .collect(Collectors.toList());
    }

    public Set<Long> refreshMembers(String key) {
        Set<Object> members = redisUtil.members(key);
        if ((Objects.isNull(members) || members.isEmpty()) && key.startsWith("3")) {
            String roomId = key.split(":")[1];
            log.info("刷新房间用户 roomId = {} ", roomId);
            try {
                BusinessResult<List<Long>> roomUserByRoomId = liveVideoService.getUserIdsByRoomId(0, Long.parseLong(roomId));
                if (roomUserByRoomId == null || roomUserByRoomId.getData() == null) {
                    return null;
                }
                List<Long> data = roomUserByRoomId.getData();
                data.stream().forEach(o -> redisUtil.addOnlineSet(key, o));
                members = new HashSet(data);
            } catch (Exception e) {
                log.error("获取房间用户失败,{}", e);
            }

        }
        return members.stream().map(o -> Long.parseLong(o.toString()) ).collect(Collectors.toSet());
    }

    public List<Long> getUserIdsByToId(String userId, String toId, String type) {
        List<Long> tempRet = new ArrayList<>();
        List<Long> result = new ArrayList<>();
        if (type.startsWith("2")) { // 群聊相关
            tempRet = getUserIdsFromGroup(toId);
        } else if (type.startsWith("3")) { // 室聊相关
            tempRet = getUserIdsFromRoom(Long.valueOf(toId));
        } else if (MessageType.DYNAMIC_CREATE_ROOM.getType().equals(type)
                || MessageType.DYNAMIC_CLOSE_ROOM.getType().equals(type)) { // 动态 创建、关闭房间
            tempRet = getUsersFriends(Long.valueOf(userId));
        }
        for (Long temp : tempRet) {
            result.add(temp);
        }
        return result;
    }

    private List<Long> getUserIdsFromRoom(Long roomId) {
        log.info("getUserIdsFromRoom start roomId={}", roomId);
        BusinessResult<List<Long>> result = liveVideoService.getUserIdsByRoomId(3, roomId);
        log.debug("getUserIdsFromRoom result={}", result);
        if (result == null) {
            return new ArrayList<>();
        }
        Long code = result.getCode();
        if (code != 0) {
            log.warn("get userIds from room abnormal! roomId={}, message={}", roomId, result.getMessage());
            return new ArrayList<>();
        }
        List<Long> data = result.getData();
        if (data != null) {
            return data;
        }
        return new ArrayList<>();
    }

    private List<Long> getUserIdsFromGroup(String groupId) {
        List<Long> retList = new ArrayList<>();
        log.info("getUserIdsFromGroup start groupId={}", groupId);
        BusinessResult<List<GroupUserVO>> result = deskMateGroupService.getGroupUserByGroupId(groupId);
        log.debug("getUserIdsFromGroup result={}", result);
        if (result == null) {
            return new ArrayList<>();
        }
        long code = result.getCode();
        if (code != 0) {
            log.warn("get userIds from group abnormal! groupId={}, message={}", groupId, result.getMessage());
            return new ArrayList<>();
        }
        List<GroupUserVO> list = result.getData();
        if (list != null) {
            for (GroupUserVO vo : list) {
                retList.add(Long.valueOf(vo.getUserId()));
            }
        }
        return retList;
    }

    private List<Long> getUsersFriends(Long userId) {
        log.info("getUsersFriends start userId={}", userId);
        BusinessResult<List<TzUserFriendInfo>> friends = userFriendService.friends(userId);
        log.debug("getUsersFriends result={}", friends);
        if (friends == null) {
            return new ArrayList<>();
        }
        if (friends.getCode() != 0) {
            log.warn("get friends userId abnormal! userId={}, message={}", userId, friends.getMessage());
            return new ArrayList<>();
        }
        List<TzUserFriendInfo> data = friends.getData();
        List<Long> userIdList = new ArrayList<>();
        if (data != null) {
            for (TzUserFriendInfo info : data) {
                userIdList.add(info.getFriendsUserId());
            }
        }
        return userIdList;
    }

    public void remove(String key, Messages msgEntity) {
        redisUtil.remove(key, Long.parseLong(msgEntity.getFromUserId()));
    }

    public void remove(String key) {
        redisUtil.delete(key);
    }

    public void addOnlineSet(String key, Messages msgEntity) {
        redisUtil.addOnlineSet(key, Long.parseLong(msgEntity.getFromUserId()));
    }
}
